package ehome_print

/*
//#cgo android CFLAGS: -I${SRCDIR}/libusb/include
//#cgo android,arm LDFLAGS: -L${SRCDIR}/libusb/armeabi-v7a -lusb1.0
//#cgo android,arm64 LDFLAGS: -L${SRCDIR}/libusb/arm64-v8a -lusb1.0
//#cgo android,386 LDFLAGS: -L${SRCDIR}/libusb/x86 -lusb1.0
//#cgo android,amd64 LDFLAGS: -L${SRCDIR}/libusb/x86_64 -lusb1.0

#include <android/log.h>
//#include <libusb.h>

#define  TAG  "IppUsb-Native"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)

static inline ehomeLog(char * a){
	LOGD(a);
}
*/
import "C"
import (
	ippusb "AndroidTest/source"
	"bytes"
	"fmt"
	"sort"
)

var (
	log       = ippusb.NewLogger().ToConsole()
	usbDevice *ippusb.Device
)

func Startup(usb_bus int, usb_dev int) {
	C.ehomeLog(C.CString("ehome print startup..."))

	log.Debug(' ', "===============================")

	var descs map[ippusb.UsbAddr]ippusb.UsbDeviceDesc
	var err = ippusb.UsbInit(true)
	if err == nil {
		descs, err = ippusb.UsbGetIppOverUsbDeviceDescs()
	}

	if err != nil {
		log.Info(0, "Can't read list of USB devices: %s", err)
	} else if descs == nil || len(descs) == 0 {
		log.Info(0, "No IPP over USB devices found")
	} else {
		// Repack into the sorted list
		var list []ippusb.UsbDeviceDesc
		var buf bytes.Buffer

		for _, desc := range descs {
			list = append(list, desc)
		}
		sort.Slice(list, func(i, j int) bool {
			return list[i].UsbAddr.Less(list[j].UsbAddr)
		})

		log.Info(0, "IPP over USB devices:")
		log.Info(0, " Num  Device              Vndr:Prod  Model")
		for i, dev := range list {
			buf.Reset()
			fmt.Fprintf(&buf, "%3d. %s", i+1, dev.UsbAddr)
			if info, err := dev.GetUsbDeviceInfo(); err == nil {
				fmt.Fprintf(&buf, "  %4.4x:%.4x  %q",
					info.Vendor, info.Product, info.MfgAndProduct)
			}

			log.Info(0, " %s", buf.String())
			log.Info(' ', "##############")
			//log.Info(0, "bus -> %d, address -> %d", dev.Bus, dev.Address)
			if usb_bus == dev.Bus && usb_dev == dev.Address {
				usbDevice, _ = ippusb.NewDevice(dev)
			} else {
				C.ehomeLog(C.CString("ehome print not startup..."))
			}

			//ippusb.StatusSet(addr, devDescs[addr], err)
		}
	}

	//ippusb.PnPStart(false)

	//printStatus()

	//if ippusb.UsbCheckIppOverUsbDevices() {
	//	ippusb.NewLogger().ToConsole().Debug(' ', "New IPP-over-USB device found")
	//}

}

func Shutdown() {
	if usbDevice != nil {
		usbDevice.Close()
		usbDevice = nil
	}
}

// printStatus prints status of running ipp-usb daemon, if any
//func printStatus() {
//	// Fetch status
//	text, err := ippusb.StatusRetrieve()
//
//	if err != nil {
//		log.Info(0, "%s", err)
//		return
//	}
//
//	// Split into lines
//	text = bytes.Trim(text, "\n")
//	lines := bytes.Split(text, []byte("\n"))
//
//	// Strip empty lines at the end
//	for len(lines) > 0 && len(lines[len(lines)-1]) == 0 {
//		lines = lines[0 : len(lines)-1]
//	}
//
//	// Write to log, line by line
//	for _, line := range lines {
//		log.Info(0, "%s", line)
//	}
//}
